package com.atguigu.video.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.video.service.VodService;
import com.atguigu.video.utils.ConstantPropertiesUtil;
import com.atguigu.video.utils.InitObject;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @PostMapping("uploadAlyiVideo")
    public R uploadAlyiVideo(MultipartFile file) {
        //返回上传视频id
        String videoId = vodService.uploadVideoAly(file);
        return R.ok().data("videoId", videoId);
    }

    @DeleteMapping("removeVideoById/{videoId}")
    public R removeVideo(@ApiParam(name = "videoId", value = "云端视频id", required = true)
                         @PathVariable String videoId) {

        vodService.removeVideo(videoId);
        return R.ok().message("视频删除成功");
    }

    @DeleteMapping("removeVideoBanth")
    public R removeVideoByIds(@ApiParam(name = "videoId", value = "云端视频id集合", required = true)
                         @RequestParam List<String> sourceIds) {

        vodService.removeVideoByIds(sourceIds);
        return R.ok().message("视频删除成功");
    }
    @GetMapping("getUploadVideoTitle/{id}")
    public String getUploadVideoTitle(@PathVariable(value = "id") String sourceId) {
        String uploadVideoName = null;
        try {
            uploadVideoName = vodService.getUploadVideoTitleBySourceId(sourceId);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return uploadVideoName;
    }

    @GetMapping("getPlayAuth/{videoId}")
    public R getVideoPlayAuth(@PathVariable("videoId") String videoId) throws Exception {

        //获取阿里云存储相关常量
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        //初始化
        DefaultAcsClient client = InitObject.initVodClient(accessKeyId, accessKeySecret);

        //请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);

        //响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);

        //得到播放凭证
        String playAuth = response.getPlayAuth();

        //返回结果
        return R.ok().message("获取凭证成功").data("playAuth", playAuth);
    }

}
